﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Threading;

namespace MapRoom
{
    public partial class RobotScanDialog : Form
    {
        public RobotScanDialog( )
        {
            InitializeComponent();
        }

        private void cancelButton_Click(object sender, EventArgs e)
        {
            if( !SerialPortControl.stopScanning )
            {
                SerialPortControl.stopRobotScan( );
            }
        }

        // This delegate enables asynchronous calls for setting
        // the text property on a TextBox control.
        delegate void SetTextCallback(string text);
        delegate void CloseFormCallback( );

        public void setStatusLabel( string statusLabel )
        {
            //label1.Text = statusLabel;
            this.SetText(statusLabel);
        }

        public void closeForm( )
        {
            if( this.InvokeRequired )
            {
                CloseFormCallback d = new CloseFormCallback(closeForm);
                this.Invoke( d );
            }
            else
            {
                this.Close( );
            }
        }

		// If the calling thread is different from the thread that
		// created the TextBox control, this method creates a
		// SetTextCallback and calls itself asynchronously using the
		// Invoke method.
		//
		// If the calling thread is the same as the thread that created
		// the TextBox control, the Text property is set directly. 

        private void SetText(string text)
        {
            // InvokeRequired required compares the thread ID of the
            // calling thread to the thread ID of the creating thread.
            // If these threads are different, it returns true.
            if (this.label1.InvokeRequired)
            {
                SetTextCallback d = new SetTextCallback(SetText);
                this.Invoke(d, new object[] { text });
            }
            else
            {
                this.label1.Text = text;
            }
        }

        private void RobotScanDialog_FormClosing(object sender, FormClosingEventArgs e)
        {
            if( !SerialPortControl.stopScanning )
            {
                SerialPortControl.stopRobotScan( );
            }

            Thread.Sleep( 100 );
        }
    }
}
